package com.fingard.dsp.bank.directbank.cib11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.*;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

public class CIB11BatPayRec extends CIB11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            StringBuilder sbFileContent = new StringBuilder();
            while (p_reqBat.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }

                String sourceNoteCode = p_reqBat.readedDetail.sourceNoteCode;
                String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);
                String certNum = p_reqBat.readedDetail.certNum;

                String tmpPayType = "";
                String recDurationPay = "";
                String oppAct = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    String tmpPayMapping = getBankConfig().getValueAsString("businessCode1988");
                    tmpPayType = getBankConfig().getMapValueByKey("businessCodeMapping1988", p_reqBat.readedDetail.srcXElement.getSingleTextNotNull(tmpPayMapping));
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    String tmpPayMapping = getBankConfig().getValueAsString("businessCode9188");
                    tmpPayType = getBankConfig().getMapValueByKey("businessCodeMapping9188", p_reqBat.readedDetail.srcXElement.getSingleTextNotNull(tmpPayMapping));

                    String durationPay = getBankConfig().getValueAsString("durationPay9188");
                    recDurationPay = getBankConfig().getMapValueByKey("durationPayMapping9188", p_reqBat.readedDetail.srcXElement.getSingleTextNotNull(durationPay));
                }
                String payAmt = p_reqBat.readedDetail.payAmount;

                String memo = p_reqBat.reqBatchNO + "-" + p_reqBat.readedDetail.askNumber;

                if ("9188".equalsIgnoreCase(p_reqBat.reqHeader.transType)) {
                    //保单合同号|证件类型|证件号码|银行账号|金额|代发代扣类型|续期缴费期数|币种|保险公司流水号|
                    sbFileContent.append(MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|", sourceNoteCode, certType, certNum, oppAct, payAmt, tmpPayType, recDurationPay, "01", memo));
                } else {
                    //保单合同号|证件类型|证件号码|银行账号|金额|代发代扣类型|币种|保险公司流水号|
                    sbFileContent.append(MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|", sourceNoteCode, certType, certNum, oppAct, payAmt, tmpPayType, "01", memo));
                }
            }
            WriteBankLogLn2("批量代收付请求文件内容:\r\n" + sbFileContent.toString());

            String cdFlag = "06";
            if (p_reqBat.reqHeader.isBatRec) {
                cdFlag = "05";
            }
            String tmpPaySendDate = Format.Date8Format.format(p_reqBat.getPayDateTime());

            String corpInitials = getBankConfig().getValueAsString("corpInitials");
            if (StringHelper.isNullOrEmpty(corpInitials)) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号:[" + p_reqBat.ownAct + "]对应的保险公司名称首字母，请检查'portfiles/CIB11/config.xml'中'corpInitials'配置是否正确!";
                return retAts;
            }
            //保险公司名称首字母_YBT_YYYYMMDD（对账日期）_ XY01（文件类型,参考码值表）_corp.txt
            String tmpUploadFileName = corpInitials + "_YBT_" + tmpPaySendDate + "_" + cdFlag + "_corp.txt";
            String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            boolean isSummaryUpload = getBankConfig().getValueAsBool("isSummaryUpload");
            if (isSummaryUpload) {
                FileHelper.appendFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
                retAts.respCode = "0";
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            } else {
                if (FileHelper.existFile(tmpLocalMarkPath)) {
                    retAts.respCode = "0";
                    retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = FailCode.E9981;
                    retAts.writeRetToATS();
                    return retAts;
                }
                String totalContent = "";
                if ("9188".equalsIgnoreCase(p_reqBat.reqHeader.transType)) {
                    // 首记录标志|保险公司编码|明细记录总笔数|总金额|备注|
                    totalContent = MessageFormat.format("F|{0}|{1}|{2}|{3}|\n", bankFront.corpNo, p_reqBat.totalNum, p_reqBat.totalAmt, "");
                } else {
                    // 首记录标志|保险公司编码|明细记录总笔数|总金额|
                    totalContent = MessageFormat.format("F|{0}|{1}|{2}|\n", bankFront.corpNo, p_reqBat.totalNum, p_reqBat.totalAmt);
                }
                FileHelper.appendFile(tmpLocalMarkPath, totalContent + sbFileContent.toString(), getCharset());

                FtpSet ftpSet = bankFront.getFtpSet("bat");
                MixFtp mixFtp = new MixFtp(ftpSet);
                FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(tmpLocalMarkPath, ftpSet.upDir, tmpUploadFileName);

                retAts.respCode = "0";
                if (!ftpReceiver.isCompleted) {
                    retAts.respCode = "-1";
                    retAts.respInfo = ftpReceiver.connMsg;
                } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                    retAts.respInfo = "上传失败";
                    retAts.transState = "BatchFailed";
                    retAts.payInfoCode = "E9999";
                } else {
                    retAts.respInfo = "上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            String tmpPaySendDate = Format.Date8Format.format(p_reqQryBat.getBgnDateTime());
            String cdFlag = "16";
            if ("9198".equalsIgnoreCase(p_reqQryBat.reqHeader.transType)) {
                cdFlag = "15";
            }

            String corpInitials = getBankConfig().getValueAsString("corpInitials");
            if (StringHelper.isNullOrEmpty(corpInitials)) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号:[" + p_reqQryBat.ownAct + "]对应的保险公司名称首字母，请检查'portfiles/CIB11/config.xml'中'corpInitials'配置是否正确!";
                return retAts;
            }
            //保险公司名称首字母_YBT_YYYYMMDD（对账日期）_ XY01（文件类型,参考码值表）_bank.txt
            String tmpDownFileName = corpInitials + "_YBT_" + tmpPaySendDate + "_" + cdFlag + "_bank.txt";
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            MixFtp mixFtp = new MixFtp(ftpSet);
            FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, tmpDownFileName, tmpLocalMarkPath);
            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while (true) {
                        String eachline = tmpReader.readLine();
                        if (StringHelper.isNullOrEmpty(eachline)) {
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            String[] bodyValues = eachline.split("\\|");

                            String askNumber = "";
                            if ("9198".equalsIgnoreCase(p_reqQryBat.reqHeader.transType)) {
                                askNumber = bodyValues[9];
                                if (p_reqQryBat.reqBatchNO.equalsIgnoreCase(askNumber.split("-")[0])) {
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.payAct = bodyValues[3];
                                    tmpRetDetail.postScript = askNumber.split("-")[1];
                                    tmpRetDetail.payAmount = bodyValues[4];
                                    tmpRetDetail.result = bodyValues[10];
                                    tmpRetDetail.payInfoCode = bodyValues[11];
                                    tmpRetDetail.memo = bodyValues[11];
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                askNumber = bodyValues[8];
                                if (p_reqQryBat.reqBatchNO.equalsIgnoreCase(askNumber.split("-")[0])) {
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.recAct = bodyValues[3];
                                    tmpRetDetail.postScript = askNumber.split("-")[1];
                                    tmpRetDetail.payAmount = bodyValues[4];
                                    tmpRetDetail.result = bodyValues[9];
                                    tmpRetDetail.payInfoCode = bodyValues[10];
                                    tmpRetDetail.memo = bodyValues[10];
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}